package com.itheima.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author by itheima
 * @Date 2022/4/27
 * @Description 定义mybatis的核心配置类
 */
//@Configuration
//@MapperScan("com.itheima.dao")
public class MybatisConfig {

    /**
     * 定义会话工厂bena，底层可获取SqlSessionFactory原始对象
     * @param ds
     * @return
     */
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource ds){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //设置pojo的包扫描
        factoryBean.setTypeAliasesPackage("com.itheima.pojo");
        //设置连接池
        factoryBean.setDataSource(ds);
        //配置分页插件
        PageInterceptor pageInterceptor=new PageInterceptor();
        Properties props=new Properties();
        //设置操作的数据库类型：实现分页时，不同的数据库有不同的实现方式，eg:mysql-->limit oracle-->不适用limit语句
        props.setProperty("helperDialect","mysql");
        //查询的当前页小于1，则默认查询首页，如果查询的页码大于最大页，则默认查询最后一页
        props.setProperty("reasonable","true");
        pageInterceptor.setProperties(props);
        Interceptor[] plugins=new Interceptor[]{pageInterceptor};
        factoryBean.setPlugins(plugins);
        return factoryBean;
    }

    /**
     * 定义扫描dao接口的配置bean，底层会自动加载dao接口，并生成代码对象，且把生成的
     * 代理对象自动加入IOC容器
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        //可写，可不写
        msc.setSqlSessionFactoryBeanName("getSqlSessionFactoryBean");
        //设置dao层的接口扫描
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }
}
